package com.l024.meet.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.l024.framework.base.BaseBackActivity;
import com.l024.framework.bmob.BmobManager;
import com.l024.framework.helper.FileHelper;
import com.l024.framework.manager.DialogManager;
import com.l024.framework.manager.PermissionManager;
import com.l024.framework.view.DialogView;
import com.l024.framework.view.LodingView;
import com.l024.meet.MainActivity;
import com.l024.meet.R;
import com.yanzhenjie.permission.FileProvider;
import com.yanzhenjie.permission.runtime.Permission;

import java.io.File;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import de.hdodenhof.circleimageview.CircleImageView;

public class FirstUploadActivity extends BaseBackActivity implements View.OnClickListener {

    private CircleImageView ivPhoto;
    private EditText etNickname;
    private Button btnUpload;
    private TextView tvCamera;
    private TextView tvAblum;
    private TextView tvCancel;

    private DialogView photoDialogView;
    private LodingView lodingView;

    private String[] permissions = {Permission.READ_EXTERNAL_STORAGE,Permission.WRITE_EXTERNAL_STORAGE,Permission.CAMERA};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_upload);
        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        ivPhoto = (CircleImageView) findViewById(R.id.iv_photo);
        etNickname = (EditText) findViewById(R.id.et_nickname);
        btnUpload = (Button) findViewById(R.id.btn_upload);
        btnUpload.setEnabled(false);
        ivPhoto.setOnClickListener(this);
        btnUpload.setOnClickListener(this);
        initPhotoView();

        etNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()>0){
                    if(uploadFile!=null){
                        btnUpload.setEnabled(true);
                    }else{
                        btnUpload.setEnabled(false);
                    }
                }
            }
        });
        //初始化上传加载框
        lodingView = new LodingView(this);
        lodingView.setLodingText("正在上传头像...");
    }

    /**
     * 初始化选择框
     *
     * @param
     */
    private void initPhotoView() {
        photoDialogView = DialogManager.getInstance().initView(this, R.layout.dialog_select_photo, Gravity.BOTTOM);
        tvCamera = (TextView) photoDialogView.findViewById(R.id.tv_camera);
        tvAblum = (TextView) photoDialogView.findViewById(R.id.tv_ablum);
        tvCancel = (TextView) photoDialogView.findViewById(R.id.tv_cancel);
        tvCamera.setOnClickListener(this);
        tvAblum.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_photo: {
                DialogManager.getInstance().show(photoDialogView);
                break;
            }
            case R.id.btn_upload: {
                //更新bmob资料
                uploadPhoto();
                break;
            }
            //拍照
            case R.id.tv_camera:{
                //申请权限
                DialogManager.getInstance().hide(photoDialogView);
                checkCaramePermission();
                break;
            }
            //相册
            case R.id.tv_ablum:{
                DialogManager.getInstance().hide(photoDialogView);
                checkAlbumPermission();
                break;
            }
            //取消
            case R.id.tv_cancel:{
                DialogManager.getInstance().hide(photoDialogView);
                break;
            }
        }
    }

    /**
     * 上传头像
     */
    private void uploadPhoto(){
        lodingView.show();
        String nickName = etNickname.getText().toString().trim();
        BmobManager.getInstance().uoloadPhoto(nickName, uploadFile, new BmobManager.OnUploadPhotoLKistener() {
            @Override
            public void OnUpdateDone() {
                //上传成功
                lodingView.hide();
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void OnUpdateFail(BmobException e) {
                //上传失败
                lodingView.hide();
                Toast.makeText(FirstUploadActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private File uploadFile = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        System.out.println("拍照返回"+requestCode);
        if(resultCode== Activity.RESULT_OK){
            if(requestCode== FileHelper.CAMEAR_REQUEST_CODE){
                uploadFile = FileHelper.getInstance().getTempFile();
                //设置头像
                if(uploadFile!=null){
                    Bitmap bitmap = BitmapFactory.decodeFile(uploadFile.getAbsolutePath());
                    ivPhoto.setImageBitmap(bitmap);
                }
            }else if(requestCode== FileHelper.ALBUM_REQUEST_CODE){
                Uri uri = data.getData();
                if(uri!=null){
                    //获取真实地址
                    String path = FileHelper.getInstance().getRealPathFromUrl(this,uri);
                    uploadFile = new File(path);
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    ivPhoto.setImageBitmap(bitmap);
                }
            }
            //判断是否设置了头像和输入了名字
            if(uploadFile!=null){
                String nickName = etNickname.getText().toString().trim();
                btnUpload.setEnabled(!TextUtils.isEmpty(nickName));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void checkCaramePermission(){
        /**
         * 申请权限
         */
        PermissionManager.requestPermission(this, new PermissionManager.PermissionQuestListener() {
            @Override
            public void onGranted() {
                FileHelper.getInstance().toCamera(FirstUploadActivity.this);
            }

            @Override
            public void onDenied(List<String> data) {
                Toast.makeText(FirstUploadActivity.this, "申请失败", Toast.LENGTH_SHORT).show();
            }
        },permissions);
    }
    private void checkAlbumPermission(){
        /**
         * 申请权限
         */
        PermissionManager.requestPermission(this, new PermissionManager.PermissionQuestListener() {
            @Override
            public void onGranted() {
                FileHelper.getInstance().toAlbum(FirstUploadActivity.this);
            }

            @Override
            public void onDenied(List<String> data) {
                Toast.makeText(FirstUploadActivity.this, "申请失败", Toast.LENGTH_SHORT).show();
            }
        },permissions);
    }
}
